import './style'
import React, { Component } from 'react'
import NativeJsBridge from 'src/assets/js/bridge'
import $http from 'src/assets/js/api'
import Toast from 'src/components/toast'


class ViewLoading extends Component {
	constructor(props) {
		super(props)

		this.state = {
			images: ['../../assets/images/bg.jpg', 
					'../../assets/images/icon_loading_chelun.png',
					'../../assets/images/icon_loading_shan.png',
					'../../assets/images/30.png',
					'../../assets/images/bg.jpg',
					'../../assets/images/bg_pakage_1.png',
					'../../assets/images/bg_pakage_2.png',
					'../../assets/images/bg_pakage_3.png',
					'../../assets/images/redpack_1.png',
					'../../assets/images/redpack_2.png',
					'../../assets/images/redpack_a.png',
					'../../assets/images/redpack_all.png',
					'../../assets/images/redpack_b.png',
					'../../assets/images/slogan_1.png',
					'../../assets/images/slogan_2.png'
					],
			progress: 0
		}
	}
	shouldComponentUpdate(nextProps, nextState) {
		return true
	}


	componentDidMount(){

		this.fakeLoading()

		let start = async () => {

			// 获取token
			let token = await this.getToken()

			// 判断是否登录，若没有登录，登录成功之后返回新的token
			let newToken = await this.isLogin(token)

			// 获取手机号码
			let userInfo = await this.getMobile(newToken)

			if(userInfo){
				let userCouponInfo = await this.getUserInfo(userInfo.mobile)
				
				if(userCouponInfo){
					clearTimeout(this.fakeLoadingInerval)

					// 开始加载图片数据
					this.loadImg(this.state.images, () => {
						if(userCouponInfo.result === '1'){
							this.props.history.push('/intro/' + userInfo.mobile)
						}else if(userCouponInfo.result === '2'){
							this.props.history.push('/coupon/' + userInfo.mobile + '/2')
						}
					})
				}

			}
		}

		start()
	}


	fakeLoading(){
		if(this.state.progress >= 20){
			clearTimeout(this.fakeLoadingInerval)
			return
		}
		this.fakeLoadingInerval = setTimeout(() => {
			this.setState({
				progress: this.state.progress + 1
			})

			this.fakeLoading()
		}, 10)
	}

	// 获取app token
	getToken() {
		return new Promise((resolve, reject) => {
			// NativeJsBridge.getToken({
			// 	callback: function(data) {
			// 		var token = data.token;
			// 		resolve(token);
			// 	}
			// });
			resolve('2436b4910a394cfbbe384be6cdb34ed19')
		});
	}

	// 获取用户的手机号码，如果用户没有登录，先进行登录操作
	isLogin(token) {
		return new Promise((resolve, reject) => {
			// if(token == '' || token == 0){
			// 	NativeJsBridge.win.login({
			// 		success: () => {
			// 			this.getToken().then((token) => {
			// 				resolve(token);
			// 			});
			// 		}
			// 	});
			// }else{
			// 	resolve(token);
			// }
			resolve('2436b4910a394cfbbe384be6cdb34ed19')
		});
	}

	// 获取手机号码
	getMobile(token){
		return $http.request({
			url: 'h5/v34/seckill/member/info',
	        method: 'post',
	        data: {
        		token: token,
            	requestId: new Date().getTime()
        	},
			headers: {
                "Accept": "application/json;version=3.0;compress=false",
                "Content-Type": "application/json;charset=utf-8"
            }
        }).then((res) => {
        	if(res.data.resCode === "000000"){
                return res.data.data
            }else if(res.data.resCode === "200008"){
                NativeJsBridge.win.login({
					success: () => {
						this.getToken().then((token) => {
							this.getMobile(token);
						});
					}
				});
            }else{
				Toast.show(res.data.resMsg)
            }
        }).catch((err) =>{
        	Toast.show('系统异常，请稍后再试')
        })
	}

	getUserInfo(mobile){
        return $http.request({
			url: 'h5/facedH5/anniversaryActivity/draw',
	        method: 'post',
            data:{
                mobile: mobile,
                optType: "1",
                requestId: new Date().getTime()
            },
            headers: {
                "Accept": "application/json;version=3.0;compress=false",
                "Content-Type": "application/json;charset=utf-8",
            }
        }).then((res) => {
        	// 1未领券   2已领券
        	if(res.data.resCode === "000000"){
                return {result: '1'}
            }else if(res.data.resCode === "110013"){
                return {result: '2'}
            }else{
            	Toast.show(res.data.resMsg)
            }
        }).catch((err) =>{
        	Toast.show('系统异常，请稍后再试')
        })
    }

	loadImg(images, callback){
		let _index = 0, progress = 20

		let onloadImg = () => {
			return new Promise((resolve, reject) => {
				var image = new Image();
				image.src = images[_index];
				image.onload = function(e){
					if(image.complete == true){
						_index ++;

						let pos = Math.floor((_index / images.length) * 100)

						progress = (pos + 20) >= 100? 100: (pos + 20)

						if(_index < images.length){
							load(images, callback);
						}else{
							if(callback && typeof callback === 'function'){
								callback();
							}
						}
						return resolve(progress)
					}
				}
			})
		}

		let load = async (images, callback) => {
			let progress = await onloadImg()
			
			this.setState({
				progress: progress
			}) 
		}


		load(images, callback)
	}

	render() {
		const { progress } = this.state
		return (
			<div className="view-loading view">
				<div className="loading">
					<div className="loading__inner">
						<div className="loading__inner__shan run"></div>
						<div className="loading__inner__chelun run"></div>
					</div>
					<p>正在加载(<span>{ progress }%</span>)</p>
				</div>
			</div>
		)
	}
}

export default ViewLoading
